import { syncSetTimeout, sendMessage, getMessage, dispatch } from "../../global/tools.js";

export default class TaskQueue {
    static count = 0;
    constructor(webController) {
        TaskQueue.count++;
        if (TaskQueue.count >= 2) {
            alert("collectionPlugin: \nError: TaskQueue.count >= 2，即将刷新页面。");
            location.reload(true);
        } 
        this.webController = webController;
        this.config = {
            callList: {},
            interval: 0,
            needCallTasks: {},
            maxCallCount: 5
        }
        this.config.needCallTasks = new Proxy(this.config.needCallTasks, {
            set: (target, key, val, receiver) => {
                Reflect.set(target, key, val, receiver);
                this.setNotice();
                return true;
            }
        });
        // 如果本地存储有callList且日期和今天一致，就把本地存储的提取出来
        {
            localforage.getItem("collectionPlugin_taskQueue_config_callList").then(localData => {
                if(localData && (localData.date == new Date().toLocaleDateString())) {
                    this.config.callList = localData.data || {};
                }; 
            });
        }
        // 页面关闭前保存数据到localforage
        window.onbeforeunload = async() => {
            localforage.setItem("collectionPlugin_taskQueue_config_callList", {
                date: new Date().toLocaleDateString(),
                data: this.config.callList
            });
        };
        this.init();
    }
    init() {
        this.eventListenersFn = {
            click: {
                title: "click",
                capture: true,
                fn: async e => {
                    if (e.target.innerText == "提交催记") {
                        const mobile = jQuery("div:contains('债务人手机号码').key").next("div.value").text().trim();;
                        const name = jQuery(".contact-refund-info p.name").eq(0).text();
                        const caseId = window.location.href.split("/").pop();
                        const custId = jQuery("div:contains('商户号').key").next("div.value").text().trim();
                        const lastCallTime = (+new Date());
                        const collectionProcess = jQuery("#refundForm label:contains('催收进程')").next("div.ivu-form-item-content").find("input").next().text();
                        const overdueDays = jQuery("li > div.key:contains('逾期天数')").next().eq(0).text();
                        const callCount = ((this.config.callList[caseId]?.callCount) ? (this.config.callList[caseId].callCount + 1) : 1);
                        this.addTask(caseId, {
                            mobile,
                            name,
                            custId,
                            lastCallTime,
                            collectionProcess,
                            overdueDays,
                            callCount
                        });
                        this.setNotice();
                    }
                }
            },
            keydown: {
                title: "keydown",
                fn: async e => {
                    if (e.key == "\\" && e.altKey) {
                        let caseId = prompt("请输入caseId:", window.location.href.split("/").pop());
                        if (!caseId) {
                            return;
                        }
                        if (!this.config.callList[caseId]) {
                            alert(`[collectionPlugin]callList[${caseId}]不存在。`);
                        }
                        if (!this.config.needCallTasks[caseId]) {
                            alert(`[collectionPlugin]needCallTasks[${caseId}]不存在。`);
                        }
                        this.deleteTask(caseId, true);
                        if (Object.keys(this.config.callList).includes(caseId)) {
                            alert(`[collectionPlugin]caseId${caseId}删除失败。`);
                        }
                    }
                }
            }
        };
        // 开始监听相关事件
        for (const key in this.eventListenersFn) {
            this.webController.document().addEventListener(this.eventListenersFn[key].title, this.eventListenersFn[key].fn, this.eventListenersFn[key].capture ? true : false);
        }
        this.addToNeedCallTasks();
        this.config.interval = setInterval(() => this.addToNeedCallTasks(), 1000 * 30);
    }
    addTask(caseId, task) {
        if ((!["未联系上", "非本人接电"].includes(task.collectionProcess)) || (task.overdueDays > 5)) {    // 当前催收进程文本不包含"未联系上"、"非本人接电"或逾期天数大于5时，则移除队列
            this.deleteTask(caseId, true);
            return;
        }
        this.config.callList[caseId] = task;
        this.deleteTask(caseId);
    }
    deleteTask(caseId, isDeleteAll = false) {
        if (isDeleteAll) {
            this.config.callList[caseId] && delete this.config.callList[caseId];
        }
        this.config.needCallTasks[caseId] && delete this.config.needCallTasks[caseId];
    }
    addToNeedCallTasks() {
        for (const key in this.config.callList) {
            let lastCallTime = (((+new Date()) - this.config.callList[key].lastCallTime) > (1000 * 60 * 30));
            if (lastCallTime && (this.config.callList[key].callCount < this.config.maxCallCount)) {
                this.config.needCallTasks[key] = this.config.callList[key];
            }
        }
    }
    setNotice() {
        VueMainInstance.$Notice.close("taskQueue");
        if (Object.keys(this.config.needCallTasks).length === 0) return;
        VueMainInstance.$Notice.open({
            name: "taskQueue",
            title: `拨打队列包含${Object.keys(this.config.needCallTasks).length}个任务`, 
            duration: 0,
            render: h => {
                return h('a', { 
                    onclick: () => {
                        let mobiles = [];
                        for (const key in this.config.needCallTasks) {
                            mobiles.push(this.config.needCallTasks[key].mobile);
                        }
                        let str = mobiles.join("\n");
                        const targetBtn1 = jQuery("div.custom-search").next().find("span:contains('重置')").parent("div.ivu-form-item-content > button");
                        if (targetBtn1.length != 1) {
                            console.error("targetBtn.length != 1");
                            return;
                        } else {
                            dispatch(targetBtn1, "click");
                        }
                        let target = jQuery("div.search-item > div.title-item > span.title:contains('手机号')").parent("div.title-item").next("div.ivu-tooltip").find("textarea");
                        if (target.length != 1) {
                            console.error("target.length != 1");
                            return;
                        }
                        target.val(str);
                        dispatch(target, "input");
                        dispatch(target, "change");
                        const targetBtn2 = jQuery("div.custom-search").next().find("span:contains('查询')").parent("div.ivu-form-item-content > button");
                        if (targetBtn2.length != 1) {
                            console.error("targetBtn.length != 1");
                            return;
                        } else {
                            dispatch(targetBtn2, "click");
                        }
                    }
                }, '点击这里去搜索')
            }
        })
    }
}